"""
DAQ设备USB连接测试程序 - Python版本
基于C版本的USB demo实现，支持DAQ125、DAQ206、DAQ207、DAQ216、DAQ217设备
"""

import time
import sys
import os

# 添加python_bind目录到路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'python_bind'))

from python_bind.usb_server_binding import USBServerBinding, DeviceType
from python_bind.daq125_binding import DAQ125Binding
from python_bind.daq206_binding import DAQ206Binding
from python_bind.daq207_binding import DAQ207Binding
from python_bind.daq216_binding import DAQ216Binding
from python_bind.daq217_binding import DAQ217Binding
from python_bind.base_device_binding import (
    LockzhinerADCVoltage,
    LockzhinerADCSampleRate,
    LockzhinerADCChannel,
    LockzhinerADCTriggerType,
    LockzhinerADCTriggerMode
)


class DeviceConfig:
    """设备配置常量"""
    # 触发类型
    TRIGGER_TYPE_DOUBLE_EDGE = LockzhinerADCTriggerType.DoubleEdge
    
    # 触发模式
    TRIGGER_MODE_COMMON = LockzhinerADCTriggerMode.Common
    
    # 触发通道
    TRIGGER_CHANNEL_NONE = LockzhinerADCChannel.ADCChannelAINNone
    
    # 触发电平
    TRIGGER_LEVEL = 100  # 100mV
    
    # 采样率
    SAMPLE_RATE_500K = LockzhinerADCSampleRate.ADCSampleRate_500_K
    
    # 电压范围
    VOLTAGE_10V = LockzhinerADCVoltage.ADCVoltage_10_V
    
    # 采集长度
    TRIGGER_LENGTH = 4920


# DLL文件路径（需要根据实际情况修改）
current_dir = os.path.dirname(os.path.abspath(__file__))
import platform
if platform.system() == "Windows":
    DLL_PATH = os.path.join(current_dir, "libdaq-4.0.0.dll")
else:
    DLL_PATH = os.path.join(current_dir, "liblibdaq-3.10.4.so")

def test_daq125():
    """测试DAQ125设备（8通道USB设备）"""
    print("开始测试DAQ125设备")
    
    # 创建USB服务器
    usb_server = USBServerBinding(DLL_PATH)
    server_handle = usb_server.create_server(DeviceType.DeviceType_DAQ125)
    if not server_handle:
        print("创建USB服务器失败")
        return False
    
    try:
        # 开始搜索设备
        usb_server.start_search(server_handle)
        
        # 等待设备连接，如果是多机，始终传入0去获取设备即可
        client_handle = None
        while usb_server.get_device_count(server_handle) > 0:
            client_handle = usb_server.get_client_by_index(server_handle, 0)
            if client_handle:
                break
            time.sleep(1.0)
        
        if not client_handle:
            print("未找到DAQ125设备")
            return False
        
        # 创建DAQ125设备
        daq125 = DAQ125Binding(DLL_PATH)
        device_handle = daq125.create_device()
        if not device_handle:
            print("创建DAQ125设备失败")
            return False
        
        try:
            # 使用后端
            if not daq125.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq125.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq125.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数
            if not daq125.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq125.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq125.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ125是8通道设备，使用0xFF开启所有通道
            channel_mask = 0xFF
            if not daq125.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq125.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC（DAQ125是8通道设备）
            acdc_channel = 0xFF  # 全通道DC
            if not daq125.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False

            # 执行采集流程
            if not daq125.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq125.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq125.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq125.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq125.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq125.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq125.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ125测试成功完成")
            return True
            
        finally:
            daq125.delete_device(device_handle)
    
    finally:
        usb_server.delete_server(server_handle)


def test_daq206():
    """测试DAQ206设备（2通道USB设备）"""
    print("开始测试DAQ206设备")
    
    # 创建USB服务器
    usb_server = USBServerBinding(DLL_PATH)
    server_handle = usb_server.create_server(DeviceType.DeviceType_DAQ206)
    if not server_handle:
        print("创建USB服务器失败")
        return False
    
    try:
        # 开始搜索设备
        usb_server.start_search(server_handle)
        
        # 等待设备连接
        client_handle = None
        while usb_server.get_device_count(server_handle) > 0:
            client_handle = usb_server.get_client_by_index(server_handle, 0)
            if client_handle:
                break
            time.sleep(1.0)
        
        if not client_handle:
            print("未找到DAQ206设备")
            return False
        
        # 创建DAQ206设备
        daq206 = DAQ206Binding(DLL_PATH)
        device_handle = daq206.create_device()
        if not device_handle:
            print("创建DAQ206设备失败")
            return False
        
        try:
            # 使用后端
            if not daq206.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq206.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq206.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数
            if not daq206.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq206.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq206.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ206是2通道设备
            channel_mask = 0x03
            if not daq206.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq206.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x03  # 全通道DC
            if not daq206.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 执行采集流程
            if not daq206.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq206.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq206.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq206.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq206.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq206.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq206.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ206测试成功完成")
            return True
            
        finally:
            daq206.delete_device(device_handle)
    
    finally:
        usb_server.delete_server(server_handle)


def test_daq207():
    """测试DAQ207设备（2通道USB设备）"""
    print("开始测试DAQ207设备")
    
    # 创建USB服务器
    usb_server = USBServerBinding(DLL_PATH)
    server_handle = usb_server.create_server(DeviceType.DeviceType_DAQ207)
    if not server_handle:
        print("创建USB服务器失败")
        return False
    
    try:
        # 开始搜索设备
        usb_server.start_search(server_handle)
        
        # 等待设备连接
        client_handle = None
        while usb_server.get_device_count(server_handle) > 0:
            client_handle = usb_server.get_client_by_index(server_handle, 0)
            if client_handle:
                break
            time.sleep(1.0)
        
        if not client_handle:
            print("未找到DAQ207设备")
            return False
        
        # 创建DAQ207设备
        daq207 = DAQ207Binding(DLL_PATH)
        device_handle = daq207.create_device()
        if not device_handle:
            print("创建DAQ207设备失败")
            return False
        
        try:
            # 使用后端
            if not daq207.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq207.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq207.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数
            if not daq207.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq207.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq207.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ207是2通道设备
            channel_mask = 0x03
            if not daq207.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq207.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x03  # 全通道DC
            if not daq207.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 执行采集流程
            if not daq207.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq207.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq207.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq207.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq207.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq207.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq207.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ207测试成功完成")
            return True
            
        finally:
            daq207.delete_device(device_handle)
    
    finally:
        usb_server.delete_server(server_handle)


def test_daq216():
    """测试DAQ216设备（4通道USB设备）"""
    print("开始测试DAQ216设备")
    
    # 创建USB服务器
    usb_server = USBServerBinding(DLL_PATH)
    server_handle = usb_server.create_server(DeviceType.DeviceType_DAQ216)
    if not server_handle:
        print("创建USB服务器失败")
        return False
    
    try:
        # 开始搜索设备
        usb_server.start_search(server_handle)
        
        # 等待设备连接
        client_handle = None
        while usb_server.get_device_count(server_handle) > 0:
            client_handle = usb_server.get_client_by_index(server_handle, 0)
            if client_handle:
                break
            time.sleep(1.0)
        
        if not client_handle:
            print("未找到DAQ216设备")
            return False
        
        # 创建DAQ216设备
        daq216 = DAQ216Binding(DLL_PATH)
        device_handle = daq216.create_device()
        if not device_handle:
            print("创建DAQ216设备失败")
            return False
        
        try:
            # 使用后端
            if not daq216.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq216.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq216.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数
            if not daq216.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq216.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq216.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ216是4通道设备
            channel_mask = 0x0F  # 0b00001111
            if not daq216.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq216.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x0F  # 全通道DC
            if not daq216.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 执行采集流程
            if not daq216.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq216.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq216.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq216.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq216.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq216.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq216.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ216测试成功完成")
            return True
            
        finally:
            daq216.delete_device(device_handle)
    
    finally:
        usb_server.delete_server(server_handle)


def test_daq217():
    """测试DAQ217设备（4通道USB设备）"""
    print("开始测试DAQ217设备")
    
    # 创建USB服务器
    usb_server = USBServerBinding(DLL_PATH)
    server_handle = usb_server.create_server(DeviceType.DeviceType_DAQ217)
    if not server_handle:
        print("创建USB服务器失败")
        return False
    
    try:
        # 开始搜索设备
        usb_server.start_search(server_handle)
        
        # 等待设备连接
        client_handle = None
        while usb_server.get_device_count(server_handle) > 0:
            client_handle = usb_server.get_client_by_index(server_handle, 0)
            if client_handle:
                break
            time.sleep(1.0)
        
        if not client_handle:
            print("未找到DAQ217设备")
            return False
        
        # 创建DAQ217设备
        daq217 = DAQ217Binding(DLL_PATH)
        device_handle = daq217.create_device()
        if not device_handle:
            print("创建DAQ217设备失败")
            return False
        
        try:
            # 使用后端
            if not daq217.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq217.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq217.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数
            if not daq217.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq217.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq217.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ217是4通道设备
            channel_mask = 0x0F  # 0b00001111
            if not daq217.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq217.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x0F  # 全通道DC
            if not daq217.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False

            # 设置超时时间
            if not daq217.config_trigger_timeout(device_handle, 100):
                print("设置超时时间失败")
                return False
            
            # 执行采集流程
            if not daq217.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq217.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq217.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq217.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq217.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq217.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq217.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ217测试成功完成")
            return True
            
        finally:
            daq217.delete_device(device_handle)
    
    finally:
        usb_server.delete_server(server_handle)


# 测试函数调用
# 如需测试其他设备，请修改此处的函数调用
if __name__ == "__main__":
    print("DAQ设备USB连接测试程序 - Python版本")
    
    # 只允许调用一个设备测试函数，通过人为控制
    # result = test_daq125()
    result = test_daq217()
    # result = test_daq206()
    # result = test_daq207()
    # result = test_daq216()
    
    if result:
        print("设备测试成功完成")
    else:
        print("设备测试失败")
